<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="auto"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户昵称" prop="name" v-if="isMec==0">
            <el-input v-model="formData.name" placeholder="请输入用户昵称" />
          </el-form-item>

          <el-form-item label="名称" prop="name" v-else>
            <el-input v-model="formData.name" placeholder="请输入名称" />
          </el-form-item>
         
          <el-form-item label="店铺名称" prop="shopName" v-if="isMec==1">
            <el-input v-model="formData.shopName"    placeholder="请输入店铺名称" />
          </el-form-item>

          <el-form-item label="登录账号" prop="account" v-if="isMec==1">
            {{formData.account}}
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="归属部门" prop="deptId">
            <el-tree-select
              v-model="formData.deptId"
              :data="deptList"
              :props="defaultProps"
              check-strictly
              node-key="id"
              placeholder="请选择归属部门"
            />
          </el-form-item>
        </el-col> -->
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="手机号码" prop="mobile">
            <el-input v-model="formData.mobile" maxlength="11" placeholder="请输入手机号码" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email" v-if="isMec==0">
            <el-input v-model="formData.email" maxlength="50" placeholder="请输入邮箱" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item v-if="formData.id === undefined&&isMec==0" label="登录账户" prop="account">
            <el-input v-model="formData.account" placeholder="请输入登录账户" />
          </el-form-item>
          <el-form-item v-if="isMec==1" label="登录账户" prop="account">
             {{formData.account}}
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-if="formData.id === undefined" label="用户密码" prop="password">
            <el-input
              v-model="formData.password"
              placeholder="请输入用户密码"
              show-password
              type="password"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="isMec==1">
        <el-col :span="24">
          <el-form-item label="营业执照名称">
            <el-input v-model="formData.shopLicenseName" placeholder="请输入营业执照名称"  />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="isMec==1">
        <el-col :span="24">
          <el-form-item label="营业执照">
            <UploadImg v-model="formData.shopLicense" :disabled="formData.isShopStatus=='1'" />
         
           <!-- <el-image class="dptx" :src="Comm.getImgOne(formData.shopLicense)"  /> -->

          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-if="isMec==1">
        <el-col :span="24">
          <el-form-item label="身份证正面">
            <UploadImg v-model="formData.card" :disabled="formData.isShopStatus=='1'" />
           <!-- <el-image class="dptx" :src="Comm.getImgOne(formData.card)"  /> -->

          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="isMec==1">
        <el-col :span="24">
          <el-form-item label="身份证背面">
            <UploadImg v-model="formData.backCard" :disabled="formData.isShopStatus=='1'" />
         
           <!-- <el-image class="dptx" :src="Comm.getImgOne(formData.backCard)"  /> -->

          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row v-if="isMec==1">
        <el-col :span="24">
          <el-form-item label="店铺营业执照编号">
           
            <el-input  :disabled="formData.isShopStatus=='1'"   v-model="formData.shopLicenseNo" placeholder="请输入店铺营业执照编号"  />

          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-if="isMec==1">
        <el-col :span="24">
          <el-form-item label="法人"> 
            <el-input  :disabled="formData.isShopStatus=='1'"   v-model="formData.shopPerson" placeholder="请输入法人"  />

          </el-form-item>
        </el-col>
      </el-row>


      <el-row v-if="isMec==1">
        <el-col :span="24">
          <el-form-item label="企业地址">
            <el-input  :disabled="formData.isShopStatus=='1'"   v-model="formData.shopAddress" placeholder="请输入企业地址"  />

          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="isMec==1">
        <el-col :span="24">
          <el-form-item label="企业主营业务">
            <el-input  :disabled="formData.isShopStatus=='1'"   v-model="formData.shopWork" placeholder="请输入主营业务"  />

          </el-form-item>
        </el-col>
      </el-row>

      
      <el-row v-if="isMec==1">
        <el-col :span="24">
          <el-form-item label="店铺联系方式">
            <el-input  :disabled="formData.isShopStatus=='1'"   v-model="formData.shopPhone" placeholder="请输入店铺联系方式"  />

          </el-form-item>
        </el-col>
      </el-row>


      <el-row v-if="isMec==1">
        <el-col :span="24">
          <el-form-item label="企业成立时间">
            <el-input  :disabled="formData.isShopStatus=='1'"   v-model="formData.shopTime" placeholder="请输入成立时间"  />

          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-if="isMec==1">
        <el-col :span="24">
          <el-form-item label="店铺业务类型">

            {{formData.shopBusinessType?formData.shopBusinessType:''}}
            <!-- <el-select v-model="formData.shopBusinessType" placeholder="请选择店铺业务类型">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.SYS_SET_MALL_MUST_UOLOAD)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select> -->
          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-if="isMec==1">
        <el-col :span="24">
          <el-form-item label="其他资质图片">
            <UploadImgs v-model="formData.otherMustImgs" :disabled="formData.isShopStatus=='1'" />
         
           <!-- <el-image class="dptx" :src="Comm.getImgOne(formData.backCard)"  /> -->

          </el-form-item>
        </el-col>
      </el-row>
      


      <el-row v-if="isMec==0">
        <el-col :span="12" >
          <el-form-item label="用户性别">
            <el-select v-model="formData.sex" placeholder="请选择">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_USER_SEX)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="岗位">
            <el-select v-model="formData.postIds" multiple placeholder="请选择">
              <el-option
                v-for="item in postList"
                :key="item.id"
                :label="item.name"
                :value="item.id!"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-else>
        
        <el-col :span="12">
          <el-form-item label="审核店铺">
            <el-select    :disabled="myRole!=-1"   v-model="formData.isShopStatus"  placeholder="请选择">
              <el-option
                v-for="item in isShopStatusList"
                :key="item.id"
                :label="item.name"
                :value="item.id!"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="isMec==1&&(myRole==-1||formData.shopCheckRemark!='')">
        <el-col :span="24">
          <el-form-item label="审核评语">
            <el-input v-model="formData.shopCheckRemark"  :disabled="myRole!=-1" placeholder="请输入审核评语"  />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="isMec==1&&formData.shopCheckTime!=null"> 
        <el-col :span="24">
          <el-form-item label="审核日期"   >
            {{timestampToDateFormat(formData.shopCheckTime)}}
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="isMec==1&&formData.shopCheckUser!=null"> 
        <el-col :span="24">
          <el-form-item label="审核人">
            {{formData.shopCheckUser}}
          </el-form-item>
        </el-col>
      </el-row>
    
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input v-model="formData.remark"  placeholder="请输入内容" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { CommonStatusEnum } from '@/utils/constants'
import { defaultProps, handleTree } from '@/utils/tree'
import * as PostApi from '@/api/system/post'
import * as DeptApi from '@/api/system/dept'
import * as UserApi from '@/api/system/user'

import { FormRules, TableColumnCtx } from 'element-plus'
import Comm from '@/utils/Comm'

defineOptions({ name: 'SystemUserForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const isMec = ref(0) // 表单的类型：create - 新增；update - 修改
const myRole= ref(-1)
console.log(getIntDictOptions(DICT_TYPE.SYS_SET_MALL_MUST_UOLOAD),"getIntDictOptions(DICT_TYPE.sys_set_mall_must_uoload)")
const thisUser=ref(Comm.getThisUser())
if(thisUser.value!=null){
   if(thisUser.value.loginUserId!=undefined&&thisUser.value.loginUserId!=null){
    if(thisUser.value.isShopStatus == '1'){
           myRole.value=1;
    }else{
           myRole.value=0;
    }
   }
}

if(location.href.indexOf("users")!=-1){
   isMec.value = 1;
}
console.log(location.href,"location.hrefups")
const isShopStatusList=ref([
   {id: "0",name:'未审核'},{id:"1",name:"审核通过"},{id:"2",name:"审核未通过"}
])
const formData = ref({
  shopLicenseNo:"",
  shopAddress:"",
  shopPerson:"",
  shopPhone:"",
  shopWork:"",
  shopTime:"",
  backCard:"",
  card:"",
  name: '',
  deptId: '',
  mobile: '',
  email: '',
  id: undefined,
  account: '',
  password: '',
  sex: undefined,
  postIds: [],
  remark: '',
  status: CommonStatusEnum.ENABLE,
  roleIds: [],
  isShopStatus:"0",
  shopCheckRemark:"",
  shopCheckTime:null,
  shopCheckUser:null,
  shopLicenseName:"",
  shopLicense:"",
  shopName:"",
  shopFaceImg:"11",
  shopBusinessType:'',
  otherMustImgs:[],
  otherMustImg:''
})

const  timestampToDateFormat = (timestamp) =>{
  const dateObj = new Date(timestamp); // 创建Date对象
  const year = dateObj.getFullYear(); // 获取年份
  const month = ("0" + (dateObj.getMonth() + 1)).slice(-2); // 获取月份，并补零
  const day = ("0" + dateObj.getDate()).slice(-2); // 获取日期，并补零
  
  return `${year}-${month}-${day}`; // 返回转换后的日期格式
}


const formRules = reactive<FormRules>({
  account: [{ required: true, message: '用户名称不能为空', trigger: 'blur' }],
  shopName: [{ required: true, message: '店铺名称不能为空', trigger: 'blur' }],
  shopFaceImg: [{ required: true, message: '店铺头像不能为空', trigger: 'blur' }],
  password: [{ required: true, message: '用户密码不能为空', trigger: 'blur' }],
  email: [
    {
      type: 'email',
      message: '请输入正确的邮箱地址',
      trigger: ['blur', 'change']
    }
  ],
  mobile: [
    {
      pattern: /^(?:(?:\+|00)86)?1(?:3[\d]|4[5-79]|5[0-35-9]|6[5-7]|7[0-8]|8[\d]|9[189])\d{8}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ]
})
const formRef = ref() // 表单 Ref
const deptList = ref<Tree[]>([]) // 树形结构
const postList = ref([] as PostApi.PostVO[]) // 岗位列表

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await UserApi.getUser(id)
      formData.value.card=Comm.getImgOne(formData.value.card);
     formData.value.backCard=Comm.getImgOne(formData.value.backCard);
    formData.value.shopLicense=Comm.getImgOne(formData.value.shopLicense);
       if(formData.value.otherMustImg){
        formData.value.otherMustImgs=Comm.getImg(formData.value.otherMustImg).split(",")
       }
    } finally {
      formLoading.value = false
    }
  }
  // 加载部门树
  deptList.value = handleTree(await DeptApi.getSimpleDeptList())
  // 加载岗位列表
  postList.value = await PostApi.getSimplePostList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async (type) => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    formData.value.card=Comm.saveImg(formData.value.card);
    formData.value.backCard=Comm.saveImg(formData.value.backCard);
    formData.value.shopLicense=Comm.saveImg(formData.value.shopLicense);
    if(formData.value.otherMustImgs&&formData.value.otherMustImgs.length>0){
      formData.value.otherMustImg=Comm.saveImg(formData.value.otherMustImgs.join(","));
    }
    const data = formData.value as unknown as UserApi.UserVO
    if (formType.value === 'create') {
     
      if(isMec.value==0){
        await UserApi.createUser(data)
        message.success(t('common.createSuccess'))
      }else{
        await UserApi.ApplyMerchant(data)
        message.success(t('common.createSuccess'))
      }
    
    } else {
      if(isMec.value==1){
        // if(type==0){
            // await UserApi.updateApplyMerchant(data)
            // message.success(t('common.updateSuccess'))
        // }
        // else{
          await UserApi.checkUser(data)
          message.success(t('common.CheckOk'))
        // }
      }else{
        await UserApi.updateUser(data)
        message.success(t('common.updateSuccess'))
      }
      
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    name: '',
    deptId: '',
    mobile: '',
    email: '',
    id: undefined,
    account: '',
    password: '',
    sex: undefined,
    postIds: [],
    remark: '',
    status: CommonStatusEnum.ENABLE,
    roleIds: []
  }
  formRef.value?.resetFields()
}
</script>
<style scoped>
.dptx{
  width: 3rem;
  height:3rem;
}
</style>
